/*
作者：黄江南
目的：
测试fcntl函数是否能够锁住已经open的文件，让子进程无法继续读取该文件
*/

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>

void printpos(char* string, int fildes)
{
	long pos;
	if( (pos=lseek(fildes, 0L, SEEK_CUR)) < 0L) {
		printf("lseek failed");
	}
	printf("%s: %ld\n", string, pos);
}

int main()
{
	int fd;
	int pid;
	char buf[10];

	fd = open("data", O_RDONLY);
	read(fd,buf,10);

	printpos("Before fork", fd);

	int res = fcntl(fd,F_SETFD,1); // set: the file can not be open by the child process

	printf("res:%d\n",res);

	printpos("Before fork and after close", fd);

	switch(pid = fork()) {
		case -1:
			perror("fork failed");
			return -1;
		case 0:
			printpos("Child before read", fd);
			
			read(fd, buf, 10);
			
			printpos("Child After read", fd);

			exit(1);
		default:
			wait(NULL);
			printf("child completed\n");

			printpos("parent After wait and before reopen and before read", fd);
			
			int res = fcntl(fd, F_SETFD, 0);
			printf("res:%d\n",res);

			read(fd, buf, 10);

			printpos("parent After wait and after reopen and after read", fd);
			exit(0);
	}

}
